// 获取模态框
var stockModal = document.getElementById("stockModal");
var editStockModal = document.getElementById("editStockModal");
var importStockModal = document.getElementById("importStockModal");

// 分页相关变量
var currentPage = 1;
var rowsPerPage = 5; // 每页显示5条记录
var allStockData = []; // 存储所有库存数据
var filteredStockData = []; // 存储筛选后的库存数据

// 打开库存详情模态框
function openStockModal(productId, productName, quantity, status, lastInTime) {
    document.getElementById("stock-product-id").textContent = productId;
    document.getElementById("stock-product-name").textContent = productName;
    document.getElementById("stock-quantity").textContent = quantity;
    document.getElementById("stock-status").textContent = status;
    document.getElementById("stock-last-in-time").textContent = lastInTime;
    stockModal.classList.add('show');
}

// 关闭库存详情模态框
function closeStockModal() {
    stockModal.classList.remove('show');
}

// 打开编辑库存信息模态框
function openEditStockModal(productId, productName, quantity, status, lastInTime) {
    document.getElementById("edit-product-id").value = productId;
    document.getElementById("edit-product-name").value = productName;
    document.getElementById("edit-quantity").value = quantity;
    document.getElementById("edit-status").value = status;
    document.getElementById("edit-last-in-time").value = lastInTime;
    editStockModal.classList.add('show');
}

// 关闭编辑库存信息模态框
function closeEditStockModal() {
    editStockModal.classList.remove('show');
}

// 保存库存信息更改
function saveStockChanges() {
    const productId = document.getElementById("edit-product-id").value;
    const productName = document.getElementById("edit-product-name").value;
    const quantity = document.getElementById("edit-quantity").value;
    const status = document.getElementById("edit-status").value;
    const lastInTime = document.getElementById("edit-last-in-time").value;

    // AJAX请求保存到服务器
    fetch('/update_stock', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            productId: productId,
            productName: productName,
            quantity: quantity,
            status: status,
            lastInTime: lastInTime
        })
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新表格中的显示
                const rows = document.querySelectorAll(".order-list tbody tr");
                rows.forEach(row => {
                    if (row.cells[1].textContent === productId) {
                        row.cells[2].textContent = productName;
                        row.cells[3].textContent = quantity;
                        row.cells[4].innerHTML = `<span class="status status-${status}">${getStatusText(status)}</span>`;
                        row.cells[5].textContent = lastInTime;
                    }
                });

                // 更新数据数组
                allStockData.forEach(item => {
                    if (item.id === productId) {
                        item.name = productName;
                        item.quantity = parseInt(quantity);
                        item.status = status;
                        item.lastInTime = lastInTime;
                    }
                });

                // 重新应用筛选
                applyFilters();

                closeEditStockModal();
                alert("库存信息已更新");
            } else {
                alert("更新失败: " + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert("发生错误，请稍后再试");
        });
}

function getStatusText(status) {
    const statusMap = {
        'in-stock': '有库存',
        'out-of-stock': '无库存',
        'low-stock': '库存不足'
    };
    return statusMap[status] || status;
}

// 打开批量导入模态框
function openImportStockModal() {
    importStockModal.classList.add('show');
}

// 关闭批量导入模态框
function closeImportStockModal() {
    importStockModal.classList.remove('show');
}

// 导出库存数据
function exportStockData() {
    // AJAX请求获取数据并导出
    const searchTerm = document.querySelector('.search-bar input').value.toLowerCase();
    const categoryFilter = document.getElementById('product-category').value;
    const statusFilter = document.getElementById('product-status').value;

    fetch('/export_stock', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            searchTerm: searchTerm,
            categoryFilter: categoryFilter,
            statusFilter: statusFilter
        })
    })
        .then(response => response.blob())
        .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = '库存数据.csv';
            a.click();
            window.URL.revokeObjectURL(url);
            alert("库存数据已导出为CSV文件");
        })
        .catch(error => {
            console.error('Error:', error);
            alert("发生错误，请稍后再试");
        });
}

// 生成库存报告
function generateStockReport() {
    // AJAX请求生成报告
    const searchTerm = document.querySelector('.search-bar input').value.toLowerCase();
    const categoryFilter = document.getElementById('product-category').value;
    const statusFilter = document.getElementById('product-status').value;

    fetch('/generate_report', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            searchTerm: searchTerm,
            categoryFilter: categoryFilter,
            statusFilter: statusFilter
        })
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(`库存报告已生成，已发送到您的邮箱\n\n统计信息:\n总商品数: ${data.report.totalItems}\n有库存: ${data.report.inStock}\n无库存: ${data.report.outOfStock}\n库存不足: ${data.report.lowStock}`);
            } else {
                alert("生成报告失败: " + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert("发生错误，请稍后再试");
        });
}

// 批量导入库存数据
function importStockData() {
    const fileInput = document.getElementById("stockFileInput");
    const file = fileInput.files[0];

    if (!file) {
        alert("请选择文件");
        return;
    }

    const formData = new FormData();
    formData.append('stockFile', file);

    fetch('/import_stock', {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert("成功导入库存数据");
                closeImportStockModal();
                // 重新加载数据
                initStockData();
            } else {
                alert("导入失败: " + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert("发生错误，请稍后再试");
        });
}

// 下载示例CSV文件
function downloadStockSampleCSV() {
    fetch('/download_sample', {
        method: 'GET'
    })
        .then(response => response.blob())
        .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = '库存数据模板.csv';
            a.click();
            window.URL.revokeObjectURL(url);
        })
        .catch(error => {
            console.error('Error:', error);
            alert("发生错误，请稍后再试");
        });
}

// 库存数据清理
function cleanStockData() {
    if (confirm("确定要清理库存数据吗？此操作将删除所有库存记录，不可撤销。")) {
        // AJAX请求清理数据
        fetch('/clean_stock', {
            method: 'POST'
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    allStockData = [];
                    filteredStockData = [];
                    updateTable();
                    alert("库存数据已清理");
                } else {
                    alert("清理失败: " + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert("发生错误，请稍后再试");
            });
    }
}

// 点击模态框外部时关闭模态框
window.onclick = function (event) {
    if (event.target == stockModal) {
        closeStockModal();
    }
    if (event.target == editStockModal) {
        closeEditStockModal();
    }
    if (event.target == importStockModal) {
        closeImportStockModal();
    }
}

// 初始化表格数据
function initStockData() {
    fetch('/get_stock_data')
        .then(response => response.json())
        .then(data => {
            allStockData = data;
            filteredStockData = [...allStockData];
            updateTable();
        })
        .catch(error => {
            console.error('Error:', error);
            alert("发生错误，请稍后再试");
        });
}

// 应用筛选条件
function applyFilters() {
    const searchTerm = document.querySelector('.search-bar input').value.toLowerCase();
    const categoryFilter = document.getElementById('product-category').value;
    const statusFilter = document.getElementById('product-status').value;

    fetch('/filter_stock', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            searchTerm: searchTerm,
            categoryFilter: categoryFilter,
            statusFilter: statusFilter
        })
    })
        .then(response => response.json())
        .then(data => {
            filteredStockData = data;
            currentPage = 1; // 重置到第一页
            updateTable();
        })
        .catch(error => {
            console.error('Error:', error);
            alert("发生错误，请稍后再试");
        });
}

// 重置筛选条件
function resetFilters() {
    document.querySelector('.search-bar input').value = '';
    document.getElementById('product-category').value = 'all';
    document.getElementById('product-status').value = 'all';

    filteredStockData = [...allStockData];
    currentPage = 1;
    updateTable();
}

// 更新表格显示
function updateTable() {
    // 隐藏所有行
    const tableRows = document.querySelectorAll(".order-list tbody tr");
    tableRows.forEach(row => {
        row.style.display = 'none';
    });

    // 显示当前页的行
    const startIndex = (currentPage - 1) * rowsPerPage;
    const endIndex = startIndex + rowsPerPage;
    const itemsToShow = filteredStockData.slice(startIndex, endIndex);

    itemsToShow.forEach(item => {
        const row = document.querySelector(`.order-list tbody tr td:nth-child(2):contains(${item.id})`).closest('tr');
        row.style.display = '';
    });

    // 更新分页信息
    updatePaginationInfo();
}

// 更新分页信息
function updatePaginationInfo() {
    const totalPages = Math.ceil(filteredStockData.length / rowsPerPage);
    document.getElementById("currentPageInfo").textContent = `当前第 ${currentPage} 页，共 ${totalPages} 页，总计 ${filteredStockData.length} 条记录`;
    renderPaginationButtons();
}

// 渲染分页按钮
function renderPaginationButtons() {
    const totalPages = Math.ceil(filteredStockData.length / rowsPerPage);
    const paginationContainer = document.querySelector('.pagination-buttons');
    paginationContainer.innerHTML = '';

    // 最多显示5个页码按钮
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, currentPage + 2);

    if (currentPage <= 3) {
        endPage = Math.min(5, totalPages);
    }
    if (currentPage >= totalPages - 2) {
        startPage = Math.max(1, totalPages - 4);
    }

    // 第一页按钮
    if (startPage > 1) {
        const firstBtn = document.createElement('button');
        firstBtn.textContent = '1';
        firstBtn.className = 'btn btn-page';
        firstBtn.onclick = () => goToPage(1);
        paginationContainer.appendChild(firstBtn);

        if (startPage > 2) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.className = 'px-2';
            paginationContainer.appendChild(ellipsis);
        }
    }

    // 中间页码按钮
    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.textContent = i;
        pageBtn.className = 'btn btn-page' + (i === currentPage ? ' bg-blue-500 text-white' : '');
        pageBtn.onclick = () => goToPage(i);
        paginationContainer.appendChild(pageBtn);
    }

    // 最后一页按钮
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.className = 'px-2';
            paginationContainer.appendChild(ellipsis);
        }

        const lastBtn = document.createElement('button');
        lastBtn.textContent = totalPages;
        lastBtn.className = 'btn btn-page';
        lastBtn.onclick = () => goToPage(totalPages);
        paginationContainer.appendChild(lastBtn);
    }
}

// 上一页
function prevPage() {
    if (currentPage > 1) {
        currentPage--;
        updateTable();
    }
}

// 下一页
function nextPage() {
    const totalPages = Math.ceil(filteredStockData.length / rowsPerPage);
    if (currentPage < totalPages) {
        currentPage++;
        updateTable();
    }
}

// 跳转到指定页
function goToPage(page) {
    const totalPages = Math.ceil(filteredStockData.length / rowsPerPage);
    if (page >= 1 && page <= totalPages) {
        currentPage = page;
        updateTable();
    }
}

// 初始化页面
document.addEventListener('DOMContentLoaded', function() {
    // 绑定按钮事件
    document.querySelector('.btn-primary-custom').addEventListener('click', exportStockData);
    document.querySelector('.btn-success').addEventListener('click', generateStockReport);

    // 绑定高级操作下拉菜单
    const dropdownBtn = document.querySelector('.dropdown button');
    const dropdownContent = document.querySelector('.dropdown-content');

    dropdownBtn.addEventListener('click', function() {
        dropdownContent.classList.toggle('show');
    });

    // 绑定下拉菜单项
    const dropdownItems = document.querySelectorAll('.dropdown-content a');
    dropdownItems[0].addEventListener('click', openImportStockModal);
    dropdownItems[1].addEventListener('click', cleanStockData);

    // 绑定表格中的编辑按钮
    document.querySelectorAll('.btn-warning').forEach(btn => {
        if (btn.textContent.trim() === '编辑') {
            btn.addEventListener('click', function() {
                const row = this.closest('tr');
                const productId = row.cells[1].textContent;
                const productName = row.cells[2].textContent;
                const quantity = row.cells[3].textContent;
                const status = row.cells[4].querySelector('span').className.includes('in-stock') ? 'in-stock' :
                    row.cells[4].querySelector('span').className.includes('out-of-stock') ? 'out-of-stock' : 'low-stock';
                const lastInTime = row.cells[5].textContent;

                openEditStockModal(productId, productName, quantity, status, lastInTime);
            });
        }
    });

    // 初始化表格数据
    initStockData();

    // 绑定搜索功能
    document.querySelector('.search-bar input').addEventListener('input', function() {
        applyFilters();
    });

    // 绑定筛选按钮
    document.getElementById('product-category').addEventListener('change', applyFilters);
    document.getElementById('product-status').addEventListener('change', applyFilters);
});